﻿/*
	Copyright 2008 CATsoft Development GmbH

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
/*
	Uitilities
*/
/***********************************************************************
 XML Http Handling
***********************************************************************/
function comm(){
	
	var request;
	var thisUrl;

	/* Initialize Communication object */
	comm.prototype.init = function()
	{
		if(request == null)
			request = new XMLHttpRequest();
			// Check if request is pending
		if ((request.readystate > 0 ) && (request.readystate < 4 ))
		{
			// Wait for 10 seconds, cancel request after this
			Sleep(10000);
			if ((request.readystate > 0 ) && (request.readystate < 4 ))
				request.abort();
		}
     }

	
    /***********************************************************************
     Call URL through XMLHttpRequest Object
    ***********************************************************************/
     comm.prototype.sendXMLHttpRequest = function(url, force, login, user, password) {
         var request = new XMLHttpRequest();
         var parser;

         try {
             if (login > '') {
                 request.open("GET", login, false, user, password);
                 request.setRequestHeader("Accept", "*/*");
                 request.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
                 request.setRequestHeader("Pragma", "no-cache");

                 request.send();
                 if (request.status != 200) {            // Login failed
                     showAlert("Error loging in to '" + login + ": ", request.status);
                     return
                 }
                 else
                     cookiescollect(request);
             }

             if ((login = '') && (user > ''))
                 request.open("GET", url, false, user, password)
             else
                 request.open("GET", url, false)

             if (force)
                 request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");

             request.setRequestHeader("Accept", "*/*");
             request.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
             request.setRequestHeader("Pragma", "no-cache");

             if (cookietostring() > "")
                 request.setRequestHeader("Cookie", cookietostring());

             request.send();
             if (request.status == 200) {
                 var xmlobject = new DOMDocument;
								xmlobject.loadXML(request.responseText);
                 parser = new SimpleXmlParser(xmlobject);
                 return parser;
             }
             else
                 showAlert("Error calling page '" + url + "': ", request.status);

         }
         catch (e) {
             showAlert("Error calling page '" + url + "': ", e.description);
         }
     }
    
	comm.prototype.sendXMLHttpRequestAsync= function( url, force, login, user, password ) {
		thisUrl = url;
		this.init()
		try {
			if( login > '' ){
				request.open("GET", login, false, user, password );
				request.setRequestHeader("Accept","*/*");
				request.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
				request.setRequestHeader("Pragma", "no-cache");

				request.send();
				if (request.status != 200) {		// Login failed
					showAlert( "Error loging in to '" + login + ": ", request.status );
					return
				}
				else
					cookiescollect( request );
			}

			if( (login = '') && (user > '' ))
				request.open("GET", url, true, user, password  )
			else
				request.open("GET", url, true )

			if(force)
				request.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" ); 
			
			request.setRequestHeader("Accept","*/*");
			request.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
			request.setRequestHeader("Pragma", "no-cache");

			if (cookietostring() > "" )
				request.setRequestHeader("Cookie", cookietostring());
			
			request.onreadystatechange = this.sendXMLHttpRequestAnswer;
			request.send();		
		}
		catch(e)
		{
			showAlert( "Error calling page '" + url + "': ", e.description); 
		}
	}

/* Get Answer */
	comm.prototype.sendXMLHttpRequestAnswer = function()
	{
		switch(request.readyState)
		{
			case 4:
							if (request.status == 200) 
							{
								var xmlobject = new DOMDocument;
								xmlobject.loadXML( request.responseText );
								parser = new SimpleXmlParser(xmlobject);
							
								if( parser != null)
									parser.parseFeed( thisUrl );
							}
							else
								showAlert( "Error calling URL : " + thisUrl + " (" + request.status + ")" );
							break;
			default:
							break;
		}
	}		
}

/***********************************************************************
 show Alert
***********************************************************************/
function showAlert( task, text ){
	var item = new ContentItem();
	item.heading = task;
	item.snippet = text;
	try{
		plugin.AddContentItem( item, gddItemDisplayAsNotification);
	}
	catch(e){
		alert( task + "/" + text )
	}
}

/***********************************************************************
 Parse Feed to debug window
***********************************************************************/
function traverse(tree) {
        if(tree.hasChildNodes()) {
                debug.info('<ul><li>');
                debug.info('<b>'+tree.tagName+' : </b>');
                var nodes=tree.childNodes.length;
                for(var i=0; i<tree.childNodes.length; i++)
                        traverse(tree.childNodes(i));
                debug.info('</li></ul>');
        }
        else
                debug.info(tree.text);
}

/***********************************************************************
 XML Escape
***********************************************************************/
function xmlEscape( s ){
var i, j;

	i = s.indexOf( "<" );
	while(i>=0){
		j = s.indexOf( ">", i);
		s = s.substring( 0, i  ) + s.substring( j + 1 );
		i = s.indexOf( "<" );
	}	
	
	// global replace throws error

	i = s.indexOf( '&' );
	while(i>=0){
		s = s.substring( 0, i  ) + "&amp;" + s.substring( i + 1 );
		i = s.indexOf( '&' , i + 1);
	}	

	i = s.indexOf( '"' );
	while(i>=0){
		s = s.substring( 0, i  ) + "&quot;" + s.substring( i + 1 );
		i = s.indexOf( '"', i  + 1);
	}	
	return s;
}

/***********************************************************************
  Replace String
***********************************************************************/
function replace(str, original, replacement) {
   var result;
   result = "";
   while(str.indexOf(original) != -1) {
      if (str.indexOf(original) > 0)
         result = result + str.substring(0, str.indexOf(original)) + replacement;
      else
         result = result + replacement;
      str = str.substring(str.indexOf(original) + original.length, str.length);
   }
   return result + str;
}

/***********************************************************************
  Get cookies from request
***********************************************************************/
function cookiescollect( request ){
   var cok="";
   var str="";
   var a=0;
   var b=0;
   try {
      str=request.getAllResponseHeaders();
	
      a = str.indexOf("Set-Cookie:") + 1;
      while (a > 0){
         b = str.indexOf("\n", a + 5 ) + 1;
         cok=str.substring(a,a + (b - a));
         cok=replace(cok,"et-Cookie: ", "");
         cok=replace(cok,"\n", "");
         cok=replace(cok,"\r", "");
         b = cok.indexOf(";")+1;
         if (b>0)
            cok=cok.substring(0,b-1)
         cookiestore(cok);

         a = str.indexOf("Set-Cookie:", a + 5)+1;
      }
   } catch (e) {
      return;
   }
}

/***********************************************************************
 store cookies
***********************************************************************/
function cookiestore(xcookie){
   var m;
   var i;
   var a=-1;
   try{
      m=xcookie.split("=");
      //for(i=0;i<0){
         cookie[icookies]=m[0];
         cookievalue[icookies]=m[1];
         icookies=icookies+1;
      /*}else{
         cookie[a]=m[0];
         cookievalue[a]=m[1];
         if(m[1]==""){
            cookie[a]="";
         }
      }*/
   } catch (e) {
      return;
   }
}

/***********************************************************************
  Cookies to String
***********************************************************************/
function cookietostring(){
   var m="";
   var i;
   try{
      for( i=0; i < icookies; i=i+1){
         if (cookie[i]!=""){
            m=m+cookie[i]+"="+cookievalue[i];
            if (i < icookies) m=m+";";
         }
      }
   } catch (e) {
      return;
   }
   return m;
}

/***********************************************************************
  Sorting
***********************************************************************/
function sortItems( a, b ) {
	if( a.date < b.date ) 
		return 1;
	else if( a.date > b.date )
		return -1;
	else
		return 0;
}

/***********************************************************************
  parse Date according to RFC 3339 
***********************************************************************/
function rfc3339StringToDate( val ){
  if (val instanceof Date) return val; 

  var year = val.substr(0,4);
  var month = val.substr(5,2) - 1;
  var day = val.substr(8,2);
  var hour = val.substr(11,2);
  var minute = val.substr(14,2);
  var second = val.substr(17,2);
  var millis = val.substr(20,3);
  var dir = val.substr(23,1);
  var offhour = val.substr(24,2);
  var offmin = val.substr(27,2);
  
  var retDate = new Date(Date.UTC(year,month,day,hour,minute,second,millis)); 
	var offset = 0;
  if (dir && offhour && offmin) 
    offset = ((offhour * 60) + offmin); 
	return Date.parse( retDate ) + offset;
}

/***********************************************************************
  Sleeps
***********************************************************************/
function Sleep(delay)
{
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}